package com.gitee.xmhzzz.component.shutdown.graceful.rabbitmq;

import com.gitee.xmhzzz.component.shutdown.graceful.event.ApplicationShutdownEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.listener.RabbitListenerEndpointRegistry;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.EventListener;

/**
 * @ClassName RabbitMqShutdown
 * @Description
 * @Author wzq
 * @Date 2023/9/25 13:41
 * @Version 1.0
 */
@Slf4j
@ConditionalOnClass(RabbitListenerEndpointRegistry.class)
@ConditionalOnProperty(value = "xmhzzz.graceful.shutdown.enable", havingValue = "true")
public class RabbitMqShutdown {
    private volatile boolean shutdown = false;

    public RabbitMqShutdown() {
        log.info("init RabbitMqShutdown");
    }

    @EventListener
    public void shutdownEventListener(ApplicationShutdownEvent applicationEvent) {
        try {
            if (!this.shutdown) {
                this.shutdown = true;
                Long beginTime = System.currentTimeMillis();
                ApplicationContext applicationContext = (ApplicationContext) applicationEvent.getSource();
                RabbitListenerEndpointRegistry rabbitListenerEndpointRegistry = applicationContext
                        .getBean(RabbitListenerEndpointRegistry.class);
                if (rabbitListenerEndpointRegistry == null) {
                    return;
                }
                log.info("rabbitMq start  beginTime [{}]", beginTime);
                rabbitListenerEndpointRegistry.stop();
                Long endTime = System.currentTimeMillis() - beginTime;
                log.info("RabbitMqShutdown  shutdown time [{}](ms)", endTime);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }
}
